<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of BUISPaceConn
 *
 * @author jianfeng
 */
class BUISpaceConn extends BUIThemedControl {

    const Relationship_Father_Space = 'father-space';
    const Relationship_Son_Space = 'son-space';
    const Show_Relationship_list = 'showRelationshipList';
    const Show_Add_Relationship = 'showAddRelationship';
    const Add_Relationship = 'addRelationship';
    const Delete_Relationship = 'deleteRelationship';

    public function onRun($data = NULL) {
        parent::onRun($data);
    }

    public function onShowRelationshipList($data = NULL) {
        $viewData = array();

        $viewData['spaceRelationshipView'] = $this->getSpaceRelationshipList();
        if (is_array($data)) {
            $viewData+=$data;
        }

        $updateControl = Blyn::app()->getUIManager()->getUpdateControl();
        $updateControl->addRenderView('spaceRelationshipList', 'spaceRelationshipList', $viewData);
    }

    public function onShowAddRelationship($data = NULL) {

        $activeLink = Blyn::app()->getUIManager()->getActiveLink();
        $rsId = $activeLink->getLinkVariable('relationshipId');

        $model = new BDynamicFormModel();
        $mySpaceIdField = 'media_mySpaceId_spaceRelationship';
        $relationshipField = 'media_relationship_spaceRelationship';

        $model->addField($mySpaceIdField);
        $model->addField($relationshipField);

        $rsTable = new BlynSheet('spaceRelationship');

        //if show exixt row
        if ($rsId != NULL) {
            $rs = $rsTable->getListById($rsId);
            $model->$mySpaceIdField = $rs->getItem('mySpaceId')->getValue();
            $model->$relationshipField = $rs->getItem('relationship')->getValue();
        }

        //populate relationData

        $viewData['model'] = $model;
        $viewData['mySpaceIdField'] = $mySpaceIdField;
        $viewData['relationshipField'] = $relationshipField;
        $viewData['relationshipData'] = $this->getRelationshipData();

        $updateControl = Blyn::app()->getUIManager()->getUpdateControl();
        $updateControl->addRenderView('spaceRelationshipAdd', 'spaceRelationshipAdd', $viewData);
    }

    public function onAddRelationship($data = NULL) {
        $postManager = new BPostManager();
        $postData = $postManager->parsedModelData();
        $updateControl = Blyn::app()->getUIManager()->getUpdateControl();

        $mediaList = $postManager->populateMediaListFromPostData($postData, 'spaceRelationship');
        $mySpaceId = $mediaList['mySpaceId']->content;
        $relationship = $mediaList['relationship']->content;

        $model = new BDynamicFormModel();
        $mySpaceIdField = 'media_mySpaceId_spaceRelationship';
        $relationshipField = 'media_relationship_spaceRelationship';

        $model->addField($mySpaceIdField);
        $model->addField($relationshipField);

        $checkResult = $this->isExistRelationship($mySpaceId, $relationship);

        $actionResult = NULL;

        if ($checkResult === FALSE) {
            $list = $this->addSpaceRelationship($mySpaceId, $relationship);
            if ($list == NULL) {
                $actionResult = 'add relationship fail';
            }
        } else {
            $actionResult = 'space exist in space relationship';
        }

        $viewData = array();
        $viewData['model'] = $model;
        $viewData['mySpaceIdField'] = $mySpaceIdField;
        $viewData['relationshipField'] = $relationshipField;
        $viewData['relationshipData'] = $this->getRelationshipData();

        if ($actionResult != NULL) {
            $viewData['actionResult'] = $actionResult;
            $updateControl->addRenderView('showAddSpaceRelationship', 'spaceRelationshipAdd', $viewData);
        } else {
            $this->onShowRelationshipList();
        }
    }

    public function onDeleteRelationship($data = NULL) {
        $activeLink = Blyn::app()->getUIManager()->getActiveLink();
        $relationshipId = $activeLink->getLinkVariable('relationshipId');

        $result = $this->deleteRelationshipById($relationshipId);
        $viewData = array();
        if ($result == FALSE) {
            $viewData['actionResult'] = $result;
        }

        $this->onShowRelationshipList($viewData);
    }

    public function getViewPath($data = NULL) {
        $theme = Blyn::app()->getUIManager()->getTheme();
        $rc = new ReflectionClass(get_class($this));
        $classPath = $rc->getFileName();

        $viewsPath = $classPath . '/ui/themes/' . $theme . '/views';

        $template = $this->getViewTemplate();
        if ($template != NULL) {
            $viewsPath.='/' . $template;
        }

        if (is_dir($viewsPath))
            return $viewsPath;
        else {
            return parent::getViewPath($data);
        }


        //return parent::getViewPath($data);
    }

    /**
     * add space as relationship to current 
     * @param type $space
     * @param type $relationship
     */
    public function addSpaceRelationship($spaceContext, $relationship) {

        $space = NULL;

        if (is_numeric($spaceContext) && $spaceContext > 0) {
            $space = new BSpace($spaceContext);
        }

        if (is_string($spaceContext) && $spaceContext != '') {
            $space = BSpace::find(array('myId' => $spaceContext));
        }

        if (is_array($spaceContext)) {
            if (isset($spaceContext['id'])) {
                $id = $spaceContext['id'];
                if (is_numeric($id) && $id > 0) {
                    $space = new BSpace($id);
                }
                if (is_string($id) && $id != '') {
                    $space = BSpace::find(array('myId' => $id));
                }
            }

            if (isset($spaceContext['mySpaceId'])) {
                $id = $spaceContext['mySpaceId'];
                if (is_numeric($id) && $id > 0) {
                    $space = new BSpace($id);
                }
                if (is_string($id) && $id != '') {
                    $space = BSpace::find(array('myId' => $id));
                }
            }

            if (isset($spaceContext['myId'])) {
                $id = $spaceContext['myId'];
                if (is_numeric($id) && $id > 0) {
                    $space = new BSpace($id);
                }
                if (is_string($id) && $id != '') {
                    $space = BSpace::find(array('myId' => $id));
                }
            }
        }

        /*
          if (is_numeric($relationshipContext) && $relationshipContext > 0) {
          $relationship = $rsTable->getListById($relationshipContext);
          }

          if (is_string($relationshipContext) && $relationshipContext != '') {
          $relationship = $rsTable->getList(array('itemData' => array(
          'relationshipName' => $relationshipContext
          )));
          if ($relationship == NULL) {
          $rsTable->addList(array('relationshipName' => $relationshipContext));
          }
          }

          if (is_array($spaceContext)) {
          $relationship = $rsTable->getList(array('itemData' => $relationshipContext));
          }
         * 
         */

        if ($space instanceof BSpace && $space->getId() > 0 && is_string($relationship) && $relationship != '') {
            if ($relationship == self::Relationship_Father_Space || $relationship == self::Relationship_Son_Space)
                return $this->addFatherSonSpace($space, $relationship);
        }

        return FALSE;
    }

    public function getSpaceRelationshipList($relationship = NULL) {
        $activeSpace = Blyn::app()->getActiveSpace();
        $itemContext = array();
        $itemContext['activeSpaceId'] = $activeSpace->getId();
        if (is_string($relationship) && $relationship != '') {
            $itemContext['relationship'] = $relationship;
        }
        //$spaceEngine = Blyn::app()->getActiveSpace()->getSpaceEngine();
        $rsTable = new BlynSheet('spaceRelationship');
        $view = $rsTable->getView(array('itemData' => $itemContext));
        return $view;
    }

    /**
     * get relationship to current space,must specify target space context
     * @param type $spaceContext
     */
    public function getSpaceRelationship($spaceContext) {
        $itemContext = array();
        if (is_string($spaceContext) && $spaceContext != '') {
            $itemContext['mySpaceId'] = $spaceContext;
        }
        if (is_array($spaceContext)) {
            $itemContext = $spaceContext;
        }
        if (is_array($itemContext) && $itemContext != NULL) {
            $itemContext['activeSpaceId'] = Blyn::app()->getActiveSpace()->getId();
        }

        $rsTable = new BlynSheet('spaceRelationship');
        $rsList = $rsTable->getList(array('itemData' => $itemContext));
        if ($rsList != NULL) {
            return $rsList->getItem('relationship')->getValue();
        }
        return FALSE;
    }

    public function deleteRelationshipById($relationshipId) {
        if (is_numeric($relationshipId) && $relationshipId != NULL) {
            $rsTable = new BlynSheet('spaceRelationship');
            $rsTable->deleteList($relationshipId);
            return $relationshipId;
        }
        return FALSE;
    }

    public function getRelationshipData($data = NULL) {
        return array(
            self::Relationship_Father_Space => 'fatherSpace',
            self::Relationship_Son_Space => 'sonSpace'
        );
    }

    protected function addFatherSonSpace($space, $relationship) {

        $rsTable = new BlynSheet('spaceRelationship');

        $itemData = array();
        $activeSpace = Blyn::app()->getActiveSpace();
        $itemData['activeSpaceId'] = $activeSpace->getId();
        $itemData['activeMySpaceId'] = $activeSpace->myId;
        $itemData['activeSpaceName'] = $activeSpace->getName();
        $itemData['spaceId'] = $space->getId();
        $itemData['mySpaceId'] = $space->myId;
        $itemData['spaceName'] = $space->name;
        $itemData['relationship'] = $relationship;

        $list = $rsTable->getList(array('itemData' => $itemData));
        if ($list == NULL)
            $list = $rsTable->addList($itemData);

        //if add father space, meanwhile add son space in couple space
        if ($relationship == self::Relationship_Father_Space) {
            $itemData['activeSpaceId'] = $space->getId();
            $itemData['activeMySpaceId'] = $space->myId;
            $itemData['activeSpaceName'] = $space->getName();
            $itemData['spaceId'] = $activeSpace->getId();
            $itemData['mySpaceId'] = $activeSpace->myId;
            $itemData['spaceName'] = $activeSpace->name;
            $itemData['relationship'] = self::Relationship_Son_Space;
            $list = $rsTable->getList(array('itemData' => $itemData));
            if ($list == NULL)
                $list = $rsTable->addList($itemData);
        }

        if ($relationship == self::Relationship_Son_Space) {
            $itemData['activeSpaceId'] = $space->getId();
            $itemData['activeMySpaceId'] = $space->myId;
            $itemData['activeSpaceName'] = $space->getName();
            $itemData['spaceId'] = $activeSpace->getId();
            $itemData['mySpaceId'] = $activeSpace->myId;
            $itemData['spaceName'] = $activeSpace->name;
            $itemData['relationship'] = self::Relationship_Father_Space;
            $list = $rsTable->getList(array('itemData' => $itemData));
            if ($list == NULL)
                $list = $rsTable->addList($itemData);
        }

        return $list;
    }

    protected function isExistRelationship($mySpaceId, $relationship = NULL) {

        $rsTable = new BlynSheet('spaceRelationship');

        $itemData = array();
        $itemData['mySpaceId'] = $mySpaceId;
        $itemData['activeSpaceId'] = Blyn::app()->getActiveSpace()->getId();
        if ($relationship != NULL) {
            if ($relationship == self::Relationship_Father_Space) {
                $itemData['relationship'] = array(
                    //space can be any of relationship
                    self::Relationship_Father_Space,
                    self::Relationship_Son_Space);
            }
        }

        //$count = $rsTable->getCount(array('itemData' => array('mySpaceId' => $mySpaceId)));
        $count = $rsTable->getCount(array('itemData' => $itemData));

        if (is_numeric($count) && $count > 0) {
            return TRUE;
        }

        return FALSE;
    }

}
